package com.huixin.zhang.common.utils;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class WordUtils {
    public static ResponseEntity<byte[]> makeSimpleWordFile(String title, String fileName, String content) throws IOException {
        XWPFDocument doc = new XWPFDocument();// 创建Word文件
        if(TextUtils.isNotBlank(title)){
            XWPFParagraph p = doc.createParagraph();// 新建段落
            p.setAlignment(ParagraphAlignment.CENTER);// 设置段落的对齐方式
            XWPFRun r = p.createRun();//创建标题
            r.setText(title);
            r.setBold(true);//设置为粗体
            r.setColor("000000");//设置颜色
            r.setFontSize(21); //设置字体大小
            r.addCarriageReturn();//回车换行
        }
        XWPFParagraph p1 = doc.createParagraph();
        p1.setAlignment(ParagraphAlignment.BOTH);
        XWPFRun c = p1.createRun();
        c.setText(content);
        c.setColor("000000");
        c.setFontSize(12);
        c.addCarriageReturn();
        String fileNameURL = URLEncoder.encode(fileName+".doc", "UTF-8");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        doc.write(out);
        byte[] byteArray = out.toByteArray();
        out.flush();
        out.close();
        doc.close();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition","attachment; filename=" + fileNameURL);
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.OK);
        return entity;
    }
}
